import {
  asyncRoutes,
  constantRoutes
} from '@/router';
import {
  getMenuCodes,
  getPermList
} from '@/api/system'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.path === '*' || route.noAuth || !route.name) return true;

  const routeObj = roles.find(item => item.permCode == route.name);
  return routeObj;
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param menuList
 */
export function filterAsyncRoutes(routes, menuList) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    const menuItem = hasPermission(menuList, tmp);
    if (menuItem) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menuList)
      }
      menuItem.permName && (tmp.meta.title = menuItem.permName);
      menuItem.icon && (tmp.meta.icon = menuItem.icon)

      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [], // 左边展示的路由菜单
  addRoutes: [],
  menuCodes: [], // 菜单权限码
  permCodes: [], // 功能权限码
}

const getters = {}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENU_CODES: (state, list) => {
    state.menuCodes = list || []
  },
  SET_PERM_CODES: (state, list) => {
    state.permCodes = list || []
  }
}

const actions = {
  generateRoutes({
    commit
  }) {
    return new Promise((resolve, reject) => {
      // 获取菜单列表
      getMenuCodes().then(({
        data
      }) => {
        let menus = data || [];
        if (!menus || menus.length == 0) {
          reject('该用户所属角色没有配置菜单，请联系管理员！')
          return;
        }

        let accessedRoutes = filterAsyncRoutes(asyncRoutes, menus);
        const permCodes = data.map(item => item.permCode);
        commit('SET_MENU_CODES', permCodes);

        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取 功能权限码
  getPermCodeList({
    commit
  }) {
    return new Promise((resolve, reject) => {
      // SET_PERM_CODE_LIST
      getPermList().then(({
        data
      }) => {
        commit('SET_PERM_CODES', data.map(el => el.permCode))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}